package com.xxchat.websocket.netty;

import com.xxchat.config.AppConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Waicc
 */
@Component
public class NettyWebSocketStarter {

    private static final Logger log = LoggerFactory.getLogger(NettyWebSocketStarter.class);

    private static final EventLoopGroup BOSS_GROUP = new NioEventLoopGroup();
    private static final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup();

    @Resource
    private HandlerHeartBeat handlerHeartBeat;

    @Resource
    private HandlerWebSocket handlerWebSocket;

    @Resource
    private AppConfig appConfig;

    @PreDestroy
    public void close() {
        BOSS_GROUP.shutdownGracefully();
        WORKER_GROUP.shutdownGracefully();
    }

    @Async("nettyTaskExecutor")
    public void start() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(BOSS_GROUP, WORKER_GROUP);
            bootstrap.channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            // 对http协议的支持，使用 http 的 编码器、解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 聚合解码 httpRequest/httpContent/lastHttpContent 到 fullHttpRequest
                            // 保证 接收的http的完整性
                            pipeline.addLast(new HttpObjectAggregator(65536));  // 64 * 1024
                            // 心跳 -> 读超时（客户端）、写超时（服务端）、总超时、单位
                            // TODO 把超时时间改回6s
                            pipeline.addLast(new IdleStateHandler(600, 0, 0, TimeUnit.SECONDS));
                            pipeline.addLast(handlerHeartBeat);
                            // 将http协议升级为ws协议，对websocket支持
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536, true, true, 10000L));
                            pipeline.addLast(handlerWebSocket);
                        }
                    });
            Integer wsPort = System.getProperty("ws.port") == null ? appConfig.getWsPort() : Integer.valueOf(System.getProperty("ws.port"));
//            ChannelFuture future = bootstrap.bind(appConfig.getWsPort()).sync();
//            log.info("Netty 服务启动成功！端口：{}", appConfig.getWsPort());
            ChannelFuture future = bootstrap.bind(wsPort).sync();
            log.info("Netty 服务启动成功！端口：{}", wsPort);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("启动Netty失败！", e);
        } finally {
            BOSS_GROUP.shutdownGracefully();
            WORKER_GROUP.shutdownGracefully();
        }
    }
}
